/*******************************************************************************************
Copyright (C) 2009 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/* 
This function finds first spectrum in the document, by its type and subtype chooses 
a layout template document to apply, applies it and prints the result.

To set up the function it is necessary to do the following: 
1. Define a directory where layout templates will be placed. Set this directory to layoutTemplatesDir variable.
2. Create layout template files which cover all your cases. 
Their names are spectral type and subtype: 1D1H.mnova, 1D13C.mnova, 2D1H13C.mnlt, etc. 
*/
function applyLayoutTemplateAndPrint(aToPDF)
{
	if (Application.version.revision < 4657)
	{
		MessageBox.critical("Your version of MNova doesn't support all the functionality of the script. Upgrade to the latest version of MNova.");
		return;
	} 

// The below settings must be changed
	layoutTemplatesDir = Dir.application();

// Find first NMR item in the document. By this item we will chose layout template document.
	var specItem;
	dw = new DocumentWindow(mainWindow.activeWindow());
	for(i = 0; i < dw.pageCount(); i++)
	{
		p = new Page(dw.page(i));
		if (p.itemCount("NMR Spectrum"))
		{
			specItem = p.item(0, "NMR Spectrum");
			break;
		}	
	}
	if (specItem == undefined)
	{
		return;
	}

// Check that appropriate layout template document exists. Expected names are 1D1H.mnova, 1D13C.mnova, 2D1H13C.mnlt, etc. 
// See more details below.
	layoutTemplateDocumentName = layoutTemplatesDir + "/" + specItem.type + specItem.subtype + ".mnova";
	if (!File.exists(layoutTemplateDocumentName))
	{
		return;
	}

// Save current document copy to the temporary directory
	tempDocName = Dir.temp() + "/applyLayoutTemplateAndPrint.mnova";
	oldFileHistory = serialization.fileHistory;
	serialization.fileHistory = false;
	serialization.save(tempDocName);

// Open previously saved document
	serialization.open(tempDocName);
	serialization.fileHistory = oldFileHistory;

// Apply layout template
	tempDw = new DocumentWindow(mainWindow.activeWindow());
	oldTemplateHistory = tempDw.templateHistory;
	tempDw.templateHistory = false;
	tempDw.applyTemplateDocument(layoutTemplateDocumentName);	
	tempDw.templateHistory = oldTemplateHistory;

// Print the result document
	if (aToPDF)
		mainWindow.doAction("action_File_ExportToPDF");
	else
		mainWindow.doAction("action_File_Print");
// Close temporary document
	mainWindow.activeWindow().close();
// Delete temporary file
	File.remove(tempDocName);
// Activate old active window 
	mainWindow.setActiveWindow(dw);
}
